package svgedit.gui.command;

import java.util.ArrayList;

import svgedit.gui.Frame;
import svgedit.svg.SVGElement;
import svgedit.svg.SVGGroup;

/**
 * Define group execution as a command object which has 
 *      execute (redo) and undo methods
 */
public class GroupCommand implements Command{
	
	private Frame frame;
	private ArrayList<SVGElement> elements;
	private ArrayList<SVGGroup> parents = new ArrayList<SVGGroup>();
	
	/**
	 *  Constructor for group command
	 *  
	 *  @param frame to get the frame object
	 * */
	public GroupCommand(Frame frame){
		this.frame = frame;
		elements = new ArrayList<SVGElement>();
	}
	
	/**
	 *  Execute to group selected elements or redo to group selected elements
	 * */
	public void execute(){
		if(elements.size() == 0){
			SVGElement[] selectElems = frame.getView().getSelectedElements();
	        // Remove elems from their current parent and add to a new
	        // group.
	        // TODO: Z-ordering is broken by this operation; group should be
	        //   inserted where the first child was
	        if (selectElems.length > 1) {
	            SVGGroup group = new SVGGroup(frame.getDocument());
	            for (SVGElement elem : selectElems) {
	            	// Backup selected elements
	            	elements.add(elem);
	            	// Backup selected elements parents
	            	parents.add(elem.getParent());
	            	// Remove elements original parent
	                elem.getParent().removeChild(elem);
	                // Add these elements into a new group
	                group.appendChild(elem);
	            }
	            // Add this new group to the root
	            frame.getDocument().getRootGroup().appendChild(group);
	            frame.getView().getDocument().setModified(true);
	            frame.getView().setSelectedElement(group);
	        }
		}else {
			if (elements.size() > 1) {
	            SVGGroup group = new SVGGroup(frame.getDocument());
	            for (SVGElement elem : elements) {
	                elem.getParent().removeChild(elem);
	                group.appendChild(elem);
	            }
	            frame.getDocument().getRootGroup().appendChild(group);
	            frame.getView().getDocument().setModified(true);
	            frame.getView().setSelectedElement(group);
	        }
		}
		 
	}
	
	/**
	 *   After grouping elements , undo is to ungroup them and back to their original parent
 	 * */
	public void undo(){
		for (int i = 0; i < elements.size(); i++){
			if(i == 0){
				// Remove this new group
				SVGGroup group = elements.get(i).getParent();
				frame.getDocument().getRootGroup().removeChild(group);
			}
			// Recover elements parent
			parents.get(i).appendChild(elements.get(i));
			frame.getView().clearSelection();
		}
	}

}
